<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Friction Example</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
        cursor: crosshair;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <canvas id="canvas" width="1024" height="768"></canvas>
    </div>

    <script type="module">
      import { LazyBrush } from 'https://cdn.jsdelivr.net/npm/lazy-brush@2.0.0/lib/lazy-brush.js'

      // The lazy radius.
      const LAZY_RADIUS = 60
      const BRUSH_RADIUS = 30

      let x = 0
      let y = 0

      // Create new LazyBrush instance.
      const lazy = new LazyBrush({
        enabled: true,
        radius: LAZY_RADIUS
      })
      const lazyFriction = new LazyBrush({
        enabled: true,
        radius: LAZY_RADIUS
      })
      const canvas = document.getElementById('canvas')

      canvas.width = window.innerWidth
      canvas.height = window.innerHeight

      canvas.addEventListener('mousemove', function (e) {
        x = e.clientX
        y = e.clientY
      })

      function loop() {
        // Update the current mouse coordinates.
        // When using friction we have to continously call the update method
        // because the brush can move even if the cursor position remains the
        // same.
        lazy.update({ x, y })
        lazyFriction.update({ x, y }, { friction: 0.5 })

        // Get the updated brush coordinates.
        const brush = lazy.getBrushCoordinates()
        const brushFriction = lazyFriction.getBrushCoordinates()

        // Draw the canvas.
        const ctx = canvas.getContext('2d')

        // Clear entire canvaas.
        ctx.clearRect(0, 0, canvas.width, canvas.height)

        // Draw brush point
        ctx.beginPath()
        ctx.fillStyle = 'red'
        ctx.arc(brushFriction.x, brushFriction.y, BRUSH_RADIUS, 0, Math.PI * 2, true)
        ctx.fill()

        // Draw the lazy radius.
        ctx.beginPath()
        ctx.strokeStyle = '#ccc'
        ctx.arc(brush.x, brush.y, LAZY_RADIUS, 0, Math.PI * 2, true)
        ctx.stroke()

        // Request next loop tick.
        requestAnimationFrame(loop)
      }

      loop()
    </script>
  </body>
</html>
